// pages/car/index.js
const app = getApp()
Page({
  data: {
    carList: [],
    manageShow: true,
    allChecked: false,
    count: 0,
    totalPrice: 0,
    checkedCount: 0,
  },
  onShow() {
    this.setData({
      count: app.car.length,
      carList: app.car
    })
    this.computeTotalPrice()
    this.computeCheckedCount()
  },
  manage() {
    this.setData({
      manageShow: !this.data.manageShow
    })
  },
  stepperChange({ detail, mark: { id } }) {
    if (detail > 100) {
      return wx.utils.toast('最大购买量为100')
    }
    if (detail < 1) {
      return wx.utils.toast('最小购买量为1')
    }

    this.setData({
      carList: this.data.carList.map(item => {
        if (item.goods_id === id) item.num = detail
        return item
      })
    })
    this.computeTotalPrice()
    app.car = this.data.carList
    wx.setStorageSync('car', JSON.stringify(this.data.carList))
  },
  checkboxChange({ detail: { value } }) {
    let allChecked = false
    if (value.length === this.data.carList.length) {
      allChecked = true
    }
    this.setData({
      allChecked
    })
    this.setData({
      carList: this.data.carList.map(item => {
        item.checked = false
        for (let i = 0; i < value.length; i++) {
          if (item.goods_id === +value[i]) {
            item.checked = true
            break
          }
        }
        return item
      })
    })
    this.computeTotalPrice()
    this.computeCheckedCount()
    app.car = this.data.carList
    wx.setStorageSync('car', JSON.stringify(this.data.carList))
  },
  allChecked({ detail: { value } }) {
    let allChecked = !!value.length
    this.setData({
      allChecked,
      carList: this.data.carList.map(item => {
        item.checked = allChecked
        return item
      })
    })
    this.computeTotalPrice()
    this.computeCheckedCount()
  },
  clearChecked() {
    if (this.data.carList.every((item => item.checked === false))) return wx.utils.toast('请选中商品')
    let newCarList = this.data.carList.filter(item => item.checked === false)
    if (newCarList.length === 0) {
      this.setData({ allChecked: false })
    }
    this.setData({
      carList: newCarList,
      count: newCarList.length
    })
    this.computeTotalPrice()
    this.computeCheckedCount()
    app.car = this.data.carList
    wx.setStorageSync('car', JSON.stringify(this.data.carList))
    wx.utils.toast('已清除选中商品', 'success')
  },
  computeTotalPrice() {
    this.setData({
      totalPrice: this.data.carList.reduce((prev, current) => {
        if (current.checked) {
          return prev + current.goods_price * current.num
        } else {
          return prev
        }
      }, 0)
    })
  },
  computeCheckedCount() {
    this.setData({
      checkedCount: this.data.carList.filter(item => item.checked === true).length
    })
  }
})